<template>
  <el-container class="home-container" v-loading="loading" element-loading-background="rgba(243, 246, 248, 0.8)">
    <vue-canvas-nest v-if="backgroundFlag" :config="configBg"></vue-canvas-nest>
<!--    <affix class="sidebar-menu" relative-element-selector="#home-header" style="width: 100%">-->
      <el-header id="home-header" class="home-header">

        <div class="logo">基于机器学习的自动摘要系统</div>
        <div class="user-info">
          <div v-if="isLogin == 'true'" class="user-info-in">
            <el-dropdown @command="handleCommand">
              <div class="el-dropdown-link">
                {{ userInfo.nickName }}<i class="el-icon-arrow-down el-icon--right"></i>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="changeInfo">信息修改</el-dropdown-item>
                <el-dropdown-item command="changePassword">修改密码</el-dropdown-item>
                <el-dropdown-item command="logOut" divided>注销</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div v-else class="to-login" @click="clickLogin">
            登录
          </div>
        </div>
        <div class="home-header-history-btn" @click="openHistory">
          历史记录
        </div>
        <el-drawer
            title="文件上传历史记录"
            :visible.sync="drawer"
            size="300px"
            :with-header="false">
          <div class="block home-header-history-line">
            <div class="radio">
              排序：
              <el-radio-group v-model="reverse">
                <el-radio :label="true" @click.native="clickNormal()">最新上传</el-radio>
                <el-radio :label="false" @click.native="clickReverse()">最早上传</el-radio>
              </el-radio-group>
            </div>
            <div v-if="isLogin == 'true'" class="history-info-container">
              <div v-for="(history, index) in localHistory" @click="clickHistory(history)" :key="index" class="history-card">
                <div class="history-icon">
                  <i v-if="history.fileType == 'pic'" class="el-icon-picture-outline"></i>
                  <i v-if="history.fileType == 'audio'" class="el-icon-microphone"></i>
                </div>
                <div class="history-info">
                  <div class="history-fileName">{{ history.fileName }}</div>
                  <div class="history-uploadTime">{{ history.uploadTime }}</div>
                </div>
              </div>
            </div>
          </div>
        </el-drawer>
      </el-header>
<!--    </affix>-->
    <el-main id="home-main" class="home-main">
      <Audio id="audio" ref="child" :userInfo="userInfo" @addHistory="addHistory"></Audio>
    </el-main>

    <el-dialog
        title="用户登录"
        :visible.sync="dialogVisibleIndex"
        width="450px"
        height="200px"
        center
        :destroy-on-close="true"
        @close="handleLogin('cancel', null)">
      <Login @loginResult="handleLogin"></Login>
    </el-dialog>
    <el-dialog title="修改信息"
               width="400px"
               :visible.sync="dialogFormVisible"
               :destroy-on-close="true"
               @closed="closeForm()">
      <el-form :model="form" label-width="80px"  size="small">
        <el-form-item label="用户名">
          <el-input :disabled="true" v-model="userInfo.userName" readonly></el-input>
        </el-form-item>
        <el-form-item label="昵称" >
          <el-input v-model="form.nickName" style="width: 100px"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="submit()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改密码"
               width="440px"
               :visible.sync="dialogPasswordVisible"
               :destroy-on-close="true">
      <el-form ref="userPasswordForm" :model="formPassword" :rules="formPasswordRules" label-width="90px"  size="small">
        <el-form-item label="用户名" prop="name">
          <el-input :disabled="true" v-model="userInfo.userName" readonly></el-input>
        </el-form-item>
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="formPassword.oldPassword" style="width: 100px"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="formPassword.newPassword" style="width: 100px"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="checkNewPassword">
          <el-input v-model="formPassword.checkNewPassword" style="width: 100px"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogPasswordVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="submitPassword()">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import md5 from 'js-md5';
import Audio from "@/components/MainPages/Audio"
import vueCanvasNest from 'vue-canvas-nest'
import Login from "@/components/Login/Login";
import {changePassword, changeUserInfo, getHistory, handleHistory} from "@/api/UserApi";

export default {
  name: "index",
  components: {Login, Audio, vueCanvasNest},
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.formPassword.checkPassword !== '') {
          this.$refs.userPasswordForm.validateField('checkPassword')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.formPassword.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      configBg: {
        color: '0,0,0',
        opacity: 0.7,
        zIndex: -2,
        count: 200,
      },
      userInfo:{},
      backgroundFlag: true,
      isLogin: 'false',
      drawer: false,
      reverse: true,
      loading: false,
      test: [],
      localHistory: [],
      dialogVisibleIndex: false,
      dialogFormVisible: false,
      dialogPasswordVisible: false,
      form:{},
      formPassword:{},
      formPasswordRules: {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
          { min: 3, max: 32, message: '长度在 3 到 16 个字符', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        checkNewPassword: [
          { validator: validatePass2, trigger: 'blur' }
        ],
      },
    }
  },
  methods: {
    clickNormal() {
      console.log("最新")
      this.localHistory.sort(function (d1, d2) {
        var time1 = new Date(d1.uploadTime.replace("-", "/").replace("-", "/"));
        var time2 = new Date(d2.uploadTime.replace("-", "/").replace("-", "/"));
        return time1 == time2 ? 0 : time1 < time2 ? 1 : -1;
      })
    },
    clickReverse() {
      console.log("最早")
      this.localHistory.sort(function (d1, d2) {
        var time1 = new Date(d1.uploadTime.replace("-", "/").replace("-", "/"));
        var time2 = new Date(d2.uploadTime.replace("-", "/").replace("-", "/"));
        return time1 == time2 ? 0 : time1 > time2 ? 1 : -1;
      })
    },
    clickLogin(){
      this.dialogVisibleIndex = true
    },
    addHistory(history) {
      this.localHistory.push(history)
      if (this.reverse) {
        this.clickNormal()
      } else {
        this.clickReverse()
      }
    },
    openHistory() {
      if (this.isLogin == "true") {
        this.drawer = true
      } else {
        this.clickLogin()
      }
    },
    handleLogin(result, userInfo){
      if(result == "success"){
        this.loginSuccess(userInfo)
        this.dialogVisibleIndex = false
      }
      if(result == "cancel"){
        this.dialogVisibleIndex = false
      }
    },
    loginSuccess(userInfo){
      this.userInfo = userInfo
      this.isLogin = 'true'
      console.log("save data")
      sessionStorage.setItem('userInfo', JSON.stringify(this.userInfo))
      sessionStorage.setItem('isLogin', this.isLogin)
      this.getHistory()
    },
    closeForm(){
      this.dialogFormVisible = false
      this.form.nickName = this.userInfo.nickName
    },
    submitPassword(){
      this.$refs['userPasswordForm'].validate((valid) => {
        if (valid) {
          console.log(this.userInfo.userName)
          changePassword(this.userInfo.userName, md5(this.formPassword.oldPassword), md5(this.formPassword.newPassword))
              .then(response => {
                let data = response.data
                if(data.code == 200){
                  this.$notify({
                    title: '密码修改成功，请重新登录',
                    duration: 2000,
                    type: 'success',
                    offset: 50,
                  });
                  this.formPassword.oldPassword = ''
                  this.formPassword.newPassword = ''
                  this.dialogPasswordVisible = false
                  sessionStorage.removeItem("isLogin");
                  sessionStorage.removeItem("userInfo");
                  this.isLogin = 'false'
                  this.userInfo = {}
                  this.$router.push('/')
                }
                if(data.code == 400){
                  this.$notify({
                    title: '旧密码错误',
                    duration: 2000,
                    type: 'warning',
                    offset: 50,
                  });
                }
              })
        }
        else {
          return false
        }
      })
    },
    logOutConfirm() {
      this.$confirm('是否要退出登录?', '注销', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        sessionStorage.removeItem("isLogin");
        sessionStorage.removeItem("userInfo");
        this.isLogin = 'false'
        this.userInfo = {}
        if (window.document.location.pathname == '/index/home/follows'){
          this.$router.push('/index/home/recommend')
        }
        this.$message({
          type: 'warning',
          message: '已退出',
          center: true,
          offset: 70
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消退出',
          center: true,
          offset: 70
        });
      });
    },
    submit(){
      if(this.form.nickName.trim() == ''){
        this.$message({
          message: '昵称不能为空字符',
          type: 'warning',
          center: true,
          offset: 70
        });
        this.form.nickName = this.userInfo.nickName
      }else if(this.form.nickName.trim() == this.userInfo.nickName){
        this.$message({
          message: '换个新的吧',
          type: 'warning',
          center: true,
          offset: 70
        });
        this.form.nickName = this.userInfo.nickName
      }else{
        let userInfo = {
          userName: this.userInfo.userName,
          nickName: this.form.nickName,
        }
        changeUserInfo(userInfo)
            .then(response => {
              let data = response.data
              if(data.code == 200){
                this.userInfo = data.data
                sessionStorage.setItem('userInfo', JSON.stringify(this.userInfo))
                this.$notify({
                  title: '成功',
                  message: "信息修改成功",
                  duration: 2000,
                  type: 'success',
                  offset: 50,
                });
              }
              this.dialogFormVisible = false
            })
      }
    },
    handleCommand(command) {
      if(command == 'logOut'){
        this.logOutConfirm()
      }
      if(command == 'changeInfo'){
        this.dialogFormVisible = true
      }
      if(command == 'changePassword'){
        this.dialogPasswordVisible = true
      }
    },
    getHistory() {
      getHistory(this.userInfo.userName)
          .then(response => {
            let data = response.data
            if (data.code == 200) {
              this.localHistory = data.data
            }
            this.clickNormal()
            if (this.reverse) {
              this.clickNormal()
            } else {
              this.clickReverse()
            }
          })
    },
    clickHistory(history) {
      this.$confirm('是否上传此文件并提取内容？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.drawer = false
        this.loading = true
        handleHistory(this.userInfo.userName, history.filePath, history.fileType, history.fileName)
          .then(res => {
            this.loading = false
            if (res.data.code === 200) {
              this.addHistory(res.data.data.fileHistory)
              if (history.fileType == "audio") {
                let resultArr =  eval('(' + res.data.data.result + ')');
                let result = resultArr[0]
                this.$refs.child.text1(result.onebest)
              }
              if (history.fileType == "pic") {
                this.$refs.child.text1(res.data.data.result)
              }
            }
            if (res.data.code === 400) {
              let resultArr =  eval('(' + res.data.message + ')');
              this.$message({
                message: resultArr.failed,
                type: 'warning',
                offset: 70,
                center: true
              });
            }
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消上传',
          center: true,
          offset: 70
        });
      });
    },
  },
  created() {
    if (sessionStorage.getItem('userInfo')) {
      this.userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
    }
    if (sessionStorage.getItem('isLogin')) {
      this.isLogin = sessionStorage.getItem('isLogin')
    }
  },
  mounted() {
    if (this.isLogin == 'true') {
      this.getHistory()
      this.clickNormal()
    }
  },
}
</script>

<style scoped>
.home-main{
  position: relative;
  height: 90%;
  overflow: hidden;
}
.home-main::-webkit-scrollbar {
  width: 8px;
  /*height: 4px;*/
}
.home-main::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: #8e8e8e;
}
.el-timeline-item /deep/ .el-timeline-item__wrapper{
  font-weight: bold;
  font-size: 15px;
  cursor: pointer;
  transition: all 0.2s;
}
.el-timeline-item /deep/ .el-timeline-item__wrapper:hover{
  margin-left: 10px;
  transform: scale(1.2);
}
.home-aside-item{
  padding-top: 10px;
  padding-bottom: 5px;
  float: left;
  width: 100%;
  height: 30px;
  transition: all 0.1s;
}
.home-aside-item:hover{
  cursor: pointer;
  transform: scale(1.3); /* 放大1.2倍 */
  font-weight: bolder;
  /*background-color: #d7d7d7;*/
  /*color: #0086b3;*/
}
.home-aside-item-words{
  font-weight: lighter;
  margin-left: 20px;
  float: left;
}
.home-aside-item-icon{
  margin-left: 20%;
  float: left;
}
.home-container{
  height: 100%;
  width: 100%;
}
.home-header{
  position: relative;
  height: 20%;
  width: 100%;
  background-color: #e2e2e2;
  box-shadow: 0px 5px 5px -5px #4e4c4c;
}
.home-aside{
  padding-top: 10px;
  height: 100%;
  box-shadow: 5px 0px 5px -5px #4e4c4c;
  overflow: hidden;
  position: relative;
}
.home-header-history-btn{
  position: absolute;
  color: #4e4c4c;
  right: 70px;
  top: 17px;
  cursor: pointer;
  font-size: 18px;
  font-weight: 600;
  transition: all 0.1s;
}
.home-header-history-btn:hover {
  transform: scale(1.2);
}
.home-header-history-line{
  margin-top: 30px;
  margin-left: 30px;
}
a {
  color: #303133;
  text-decoration: #303133;
}
.beside-aside{
  position: absolute;
  top: 15px;
  right: 0;
  height: 35px;
  width: 4px;
  background: #4e4c4c;
  transition: all 0.3s;
  transform: translateY(0px);
}
.switch-bg{
  width: 200px;
  position: absolute;
  top: 30%;
  left: 20px;
}
.switch-name{
  font-weight: lighter;
  float: left;
  font-size: 15px;
}
.switch-switch{
  float: left;
  margin-left: 10px;
}
.logo{
  position: absolute;
  cursor: pointer;
  top: 10px;
  left: 50px;
  font-weight: bold;
  font-size: 27px;
}
.user-info{
  position: absolute;
  color: #8e8e8e;
  top: 17px;
  right: 200px;
}
.el-dropdown-link{
  cursor: pointer;
  font-size: 18px;
  font-weight: 600;
  transition: all 0.2s;
}
.el-dropdown-link:hover{
  transform: scale(1.2);
}
.to-login{
  cursor: pointer;
  font-size: 18px;
  font-weight: 600;
  transition: all 0.1s;
}
.to-login:hover{
  transform: scale(1.2);
}
.history-card{
  position: relative;
  margin-top: 10px;
  margin-bottom: 20px;
  height: 80px;
  width: 250px;
  border-radius: 15px;
  background-color: #e7e7e7;
  box-shadow: #666 0px 0px 5px;
  transition: all 0.1s;
  margin-left: 30px;
}
.history-card:hover {
  cursor: pointer;
  transform: scale(1.05);
}
.history-info{
  position: absolute;
  top: 3px;
  left: 88px;
  right: 20px;
  bottom: 10px;
}
.history-icon{
  position: absolute;
  width: 80px;
  top: -7px;
  bottom: 10px;
  left: 10px;
  font-size: 70px;
}
.history-fileName{
  margin-top: 10px;
  font-weight: bold;
  font-size: 18px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.history-uploadTime{
  margin-top: 10px;
  width: 100%;
  font-weight: lighter;
  font-size: 15px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.el-drawer /deep/ .el-drawer__body{
  height: 100%;
}
.history-info-container{
  position: absolute;
  top: 60px;
  bottom: 0px;
  overflow: auto;
  overflow-x: hidden;
  right: 0px;
  width: 300px;
}
.el-main{
  padding: 0px;
}
</style>
